package com.UI;

import java.util.Calendar;
import com.Model.CurricularDbAdapter;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.database.Cursor;

/*creating TA/GA hours for each course*/

public class ExtraCurricularForm extends Activity {
	/** Called when the activity is first created. */
	
    private TextView startTimeDisplay;
    public Button pickTime;
    private int startHour, startMinute;
    String days = "";    
    static final int TIME_DIALOG_ID = 1;
	
	private TextView startDateDisplay;
	private Button pickDate;
	private int mYear;
	private int mMonth;
	private int mDay;
	static final int DATE_DIALOG_ID = 0;

	private EditText nameText;
	private TextView dayText;
	private TextView timeText;
	private EditText locationText;
	private EditText commentsText;
	private Long RowId;
	private CurricularDbAdapter DbHelper;
		
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		 	requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
	        setContentView(R.layout.add_curricular_form);
	    	getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.curricular_formtitlebar);
		
	    	((TextView)findViewById(R.id.titleCurricular)).setText("Extra Curricular Activities" );
		
	    	findViewById(R.id.back).setOnClickListener(new OnClickListener() {
	    		public void onClick(View v) {
	    			ExtraCurricularForm.this.finish();

	    		}
	    	});
	    	
		    DbHelper = new CurricularDbAdapter(this);
	        DbHelper.open();
	  //      setContentView(R.layout.add_curricular_form);     
	        nameText = (EditText) findViewById(R.id.txtAddName);
	        dayText = (TextView) findViewById(R.id.dateDisplay);
	        timeText = (TextView) findViewById(R.id.startTimeDisplay);
	        locationText = (EditText) findViewById(R.id.txteLocation);
	        commentsText = (EditText) findViewById(R.id.txteComments);
				
		// capture our View elements
        startDateDisplay = (TextView) findViewById(R.id.dateDisplay); 
		pickDate = (Button) findViewById(R.id.pickDate);
		     
        startTimeDisplay = (TextView) findViewById(R.id.startTimeDisplay);        
        pickTime = (Button) findViewById(R.id.startTime);

        Button confirmButton = (Button) findViewById(R.id.btnCurricularSubmit);
        
        if(savedInstanceState != null){
        	RowId=savedInstanceState.getLong(CurricularDbAdapter.KEY_ROWID);
        }
        else{
        	RowId=null;
        }

		if (RowId == null) {
			Bundle extras = getIntent().getExtras();  
			
			if(extras != null){
				RowId=extras.getLong(CurricularDbAdapter.KEY_ROWID); 
			}
		else {
			RowId=null;
		}
		}

		populateFields();
		
        confirmButton.setOnClickListener(new View.OnClickListener() {

        	public void onClick(View view) {
        	    setResult(RESULT_OK);
        	    finish();
        	}         
        });
 

        
		// add a click listener to the button
		pickDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		
		// add a click listener to the button
		pickTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});
		
		// get the current date
		final Calendar c1 = Calendar.getInstance();
		mYear = c1.get(Calendar.YEAR);
		mMonth = c1.get(Calendar.MONTH);
		mDay = c1.get(Calendar.DAY_OF_MONTH);
		
		// display the current date
		updateDateDisplay();

        // get the current time
        final Calendar c2 = Calendar.getInstance();
        startHour = c2.get(Calendar.HOUR_OF_DAY);
        startMinute = c2.get(Calendar.MINUTE);
        
        // display the current time
        updateDisplay();
		

	} // onCreate method

    // display Activity in the editor
    private void populateFields() {
        if (RowId != null) {
            Cursor activity = CurricularDbAdapter.fetchActivity(RowId);
            startManagingCursor(activity);
            nameText.setText(activity.getString(
            		activity.getColumnIndexOrThrow(CurricularDbAdapter.KEY_NAME)));
            dayText.setText(activity.getString(
            		activity.getColumnIndexOrThrow(CurricularDbAdapter.KEY_DAY)));
            timeText.setText(activity.getString(
            		activity.getColumnIndexOrThrow(CurricularDbAdapter.KEY_TIME)));
            locationText.setText(activity.getString(
            		activity.getColumnIndexOrThrow(CurricularDbAdapter.KEY_LOCATION)));
            commentsText.setText(activity.getString(
            		activity.getColumnIndexOrThrow(CurricularDbAdapter.KEY_COMMENTS)));       
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(CurricularDbAdapter.KEY_ROWID, RowId);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        saveState();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        populateFields();
    }
    
    
    private void saveState() {
        String name = nameText.getText().toString();
        String day = dayText.getText().toString();
        String time = timeText.getText().toString();
        String location = locationText.getText().toString();
        String comments = commentsText.getText().toString();


        if (RowId == null) {
            long id = DbHelper.createActivity(name, day, time, location, comments);
            if (id > 0) {
                RowId = id;
            }
        } else {
            DbHelper.updateActivity(RowId, name, day, time, location, comments);
        }
    }

	
	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			startHour = hourOfDay;
			startMinute = minute;
			updateDisplay();
		}
	};

	// the call back received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDateDisplay();
		}
	};

	// updates the date in the TextView
	private void updateDateDisplay() {  
		
		String month;
		switch (mMonth){
			case 0:  month = "Jan"; break;
		    case 1:  month = "Feb"; break;
		    case 2:  month = "Mar"; break;
		    case 3:  month = "Apr"; break;
		    case 4:  month = "May"; break;
		    case 5:  month = "Jun"; break;
		    case 6:  month = "Jul"; break;
		    case 7:  month = "Aug"; break;
		    case 8:  month = "Sep"; break;
		    case 9: month = "Oct"; break;
		    case 10: month = "Nov"; break;
		    case 11: month = "Dec"; break;
		    default: month = "Invalid month.";break;    
         }
		
		startDateDisplay.setText(new StringBuilder()
				// Month is 0 based so add 1
				
				.append(month).append("-").append(mDay).append("-")
				.append(mYear).append(" "));
	}

	// updates the time we display in the TextView
	private void updateDisplay() {
		
		String ampm;
		String displayHour = null;
		
		if(startHour <12){
			ampm = "AM";
		}
		else {
			ampm = "PM";
		}
		
		switch(startHour){
		
		case 00: displayHour = "12"; break;
		case 01: displayHour = "1"; break;
		case 02: displayHour = "2"; break;
		case 03: displayHour = "3"; break;
		case 04: displayHour = "4"; break;
		case 05: displayHour = "5"; break;
		case 06: displayHour = "6"; break;
		case 07: displayHour = "7"; break;
		case 8: displayHour = "8"; break;
		case 9: displayHour = "9"; break;
		case 10: displayHour = "10"; break;
		case 11: displayHour = "11"; break;
		case 12: displayHour = "12"; break;
		case 13: displayHour = "1"; break;
		case 14: displayHour = "2"; break;
		case 15: displayHour = "3"; break;
		case 16: displayHour = "4"; break;
		case 17: displayHour = "5"; break;
		case 18: displayHour = "6"; break;
		case 19: displayHour = "7"; break;
		case 20: displayHour = "8"; break;
		case 21: displayHour = "9"; break;
		case 22: displayHour = "10"; break;
		case 23: displayHour = "11"; break;
		case 24: displayHour = "12"; break;
		}
		
		
		
		startTimeDisplay.setText(new StringBuilder().append(displayHour).append(":")
				.append(pad(startMinute)).append(" ").append(ampm));
	}

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == DATE_DIALOG_ID) {
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		} 
		else if (id == TIME_DIALOG_ID) {
			return new TimePickerDialog(this, mTimeSetListener, startHour, startMinute,
					false);
		}
		return null;
	}

}
